// place files you want to import through the `$lib` alias in this folder.

import type { Klt } from "./bindings";
import { DateTime } from 'luxon';

export const KLINE_INIT_SIZE = 168;

export function isValidKlt(str: string | null | undefined): str is Klt {
    if (str === null || str === undefined) {
        return false;
    }
    return ["M001", "M005", "M015", "M030", "M060", "M120", "DAY", "WEEK", "MONTH"].includes(str);
}
export function convertToKlt(str: string | null | undefined): Klt {
    if (isValidKlt(str)) {
        return str as Klt;
    } else {
        return "DAY"; // Or handle the error as appropriate
    }
}


export class LimitedQueue<T> {
    private queue: T[] = [];
    private maxLimit: number;

    constructor(maxLimit: number) {
        if (maxLimit <= 0) throw new Error("Limit must be greater than 0");
        this.maxLimit = maxLimit;
    }

    // Enqueue supports adding multiple items, allowing duplicates, and dequeues oldest when full
    enqueue(items: T[]): void {
        items.forEach(item => {
            this.queue.push(item);
            // If the queue exceeds the limit, dequeue the oldest item
            if (this.queue.length > this.maxLimit) {
                this.queue.shift();
            }
        });
    }

    // Dequeue specific items, supporting an array of items to remove
    dequeue(items: T[]): void {
        items.forEach(item => {
            const index = this.queue.indexOf(item);
            if (index !== -1) {
                this.queue.splice(index, 1);
            }
        });
    }

    // Check if all provided items are present in the queue
    contains(items: T[]): boolean {
        return items.every(item => this.queue.includes(item));
    }

    *[Symbol.iterator](): Iterator<[number, T]> {
        for (let i = 0; i < this.queue.length; i++) {
            yield [i, this.queue[i]];
        }
    }
    get size(): number {
        return this.queue.length;
    }
}



// Helper function to format date
export function formatDate(dateString: string | number | Date) {
    return new Date(dateString).toLocaleDateString()
}


export function format_datetime(prefix: string, klts: string, klt: Klt) {
    let format = "yyMM-dd HH:mm";
    if (klt === "DAY" || klt === "WEEK" || klt === "MONTH") {
        format = "yyMM-dd";
    }

    let klts_dt = DateTime.fromISO(klts)
        .setZone('utc') // Ensure it's in UTC before formatting
        .toFormat(format); // Convert the string to DateTime
    return prefix + " " + klts_dt

}